<?php
/**代码生成
 * Created by leiying
 * Date: 2018/1/24
 * Time: 11:06
 */

namespace Admin\Controller;


class CodeController extends AdminController
{
    /**生成CRUD
     * @author leiying
     */
    public function crud(){
        //确定当前步骤,没有传递，当前默认进入第一步
        $step = I('get.step','table');
        /*获取顶级菜单的信息*/
        $lists = M('menu')->where(array('hide'=>0,'pid'=>0))->order('sort')->select();
        $res =list_to_tree($lists,'m_id');//处理成分级的嵌套数组
        //处理成一维数组
        $pids = tree_to_array($res);
        $this->assign('pids',$pids);

        //步骤为table的时候执行
        if($step == 'table'){
            if(IS_POST){
                //检测表是否存在
                $table = I('post.table','');
                if($table == ''){
                    $this->error('表名不能为空');
                }
                $isTable = M()->query('SHOW TABLES LIKE "'.C('DB_PREFIX').$table.'"');
                if( $isTable ){
                    $sql = 'SELECT COLUMN_NAME,COLUMN_COMMENT,COLUMN_DEFAULT,EXTRA,COLUMN_KEY FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = "'.C('DB_NAME').'" AND TABLE_NAME = "'.C('DB_PREFIX').$table.'"';
                    $info = M()->query($sql);

                    foreach($info as &$v){
                        if($v['EXTRA'] == 'auto_increment'){
                            $v["COLUMN_DEFAULT"] = '自增长';
                        }
                        if($v['COLUMN_KEY'] == 'PRI'){
                            $v["COLUMN_DEFAULT"] = '主键,自增长';
                        }
                        if($v['COLUMN_DEFAULT'] === ''){
                            $v["COLUMN_DEFAULT"] = '空字符串';
                        }
                        unset($v['EXTRA']);
                        unset($v['COLUMN_KEY']);
                    }
                    $this->success($info);
                }else{
                    $this->error('表不存在');
                }
            }else{

                $this->assign('step','table');
                $this->display();
            }
        }
        //步骤为field的时候执行
        elseif($step == 'field'){
            if(IS_POST){
                $post = I('post.');

                echo '<p style="color:blue">页面生成中，请等待...\n</p>';ob_flush();flush();

                //生成代码
                $model = M($post['table_name']);
                $controllerName = $modelName = implode(array_map('ucfirst',explode('_',$post['table_name'])));
                //不考虑复合主键，只考虑存在一个主键的情况
                $pkField = $model->getPk();
                //3、获取当前的字段列表
                $nameField = I('post.field_name');
                $titleField = I('post.field_title');
                $listField = I('post.is_list','');//列表的字段
                $setField = I('post.is_set','');//设置的字段
                $searchField = I('post.is_search','');//搜索的字段
                $sortField = I('post.is_sort','');//排序的字段
                //4、获取表对应的展示标题
                $tableTitle = $post['title'];
                //获取面包屑导航
                $nav_title = M("menu")->where(array("m_id"=>$post['pid']))->getField("title");


                //记录需要替换的对应内容
                $search = array('__CONTROLLER__','__PK_FIELD__','__TITLE__','__TABLE__','__NOW_DATE__','__NOW_TIME__','__NAV_TITLE__');
                $replace = array($controllerName,$pkField,$tableTitle,$post['table_name'],date("Y-m-d",time()),date("H:i:s",time()),$nav_title);
                //生成代码
                $controller1 = '';
                $controller2 = '';
                $controller3 = '';
                $controller4 = '';
                $controller5 = '            $data = array(
                \'add_time\'=>time(),
';
                $controller6 = '';
                $controller7 = '';
                $template = APP_PATH . 'Admin/View/Code/controller1.template';
                $content = file_get_contents($template);
                $controller1 .= str_replace($search,$replace,$content);

                $template = APP_PATH . 'Admin/View/Code/controller3.template';
                $content = file_get_contents($template);
                $controller3 .= str_replace($search,$replace,$content);

                $template = APP_PATH . 'Admin/View/Code/controller6.template';
                $content = file_get_contents($template);
                $controller6 .= str_replace($search,$replace,$content);

                $template = APP_PATH . 'Admin/View/Code/controller7.template';
                $content = file_get_contents($template);
                $controller7 .= str_replace($search,$replace,$content);

                $view_list1 = '';
                $view_list2 = '';
                $view_list3 = '';
                $view_list45 = '';
                $view_list6 = '';
                $view_list7 = '';
                $view_list8 = '';
                $template = APP_PATH . 'Admin/View/Code/view_list1.template';
                $content = file_get_contents($template);
                $view_list1 .= str_replace($search,$replace,$content);

                $template = APP_PATH . 'Admin/View/Code/view_list3.template';
                $content = file_get_contents($template);
                $view_list3 .= str_replace($search,$replace,$content);

                $template = APP_PATH . 'Admin/View/Code/view_list6.template';
                $content = file_get_contents($template);
                $view_list6 .= str_replace($search,$replace,$content);

                $template = APP_PATH . 'Admin/View/Code/view_list8.template';
                $content = file_get_contents($template);
                $view_list8 .= str_replace($search,$replace,$content);

                $view_add1 = '';
                $view_add2 = '';
                $view_add3 = '';

                $template = APP_PATH . 'Admin/View/Code/view_add1.template';
                $content = file_get_contents($template);
                $view_add1 .= str_replace($search,$replace,$content);

                $template = APP_PATH . 'Admin/View/Code/view_add3.template';
                $content = file_get_contents($template);
                $view_add3 .= str_replace($search,$replace,$content);

                $view_edit1 = '';
                $view_edit2 = '';
                $view_edit3 = '';

                $template = APP_PATH . 'Admin/View/Code/view_edit1.template';
                $content = file_get_contents($template);
                $view_edit1 .= str_replace($search,$replace,$content);

                $template = APP_PATH . 'Admin/View/Code/view_edit3.template';
                $content = file_get_contents($template);
                $view_edit3 .= str_replace($search,$replace,$content);


                //搜索
                if(!empty($searchField)){
                    foreach($searchField as $sort){
                        $search = array('__FIELD__','__FIELD_TITLE__');
                        $replace = array($nameField[$sort],$titleField[$sort]);

                        $template = APP_PATH . 'Admin/View/Code/controller2.template';
                        $content = file_get_contents($template);
                        $controller2 .= str_replace($search,$replace,$content);

                        $template = APP_PATH . 'Admin/View/Code/view_list2.template';
                        $content = file_get_contents($template);
                        $view_list2 .= str_replace($search,$replace,$content);
                    }
                    $template = APP_PATH . 'Admin/View/Code/view_list2_1.template';
                    $content = file_get_contents($template);
                    $view_list2 .= str_replace($search,$replace,$content);
                }
                //列表
                if(!empty($listField)){
                    foreach($listField as $list){
                        $search = array('__FIELD__','__FIELD_TITLE__','__CONTROLLER__');
                        $replace = array($nameField[$list],$titleField[$list],$controllerName);

                        if(!empty($sortField) && in_array($list,$sortField)){
                            $template = APP_PATH . 'Admin/View/Code/view_list5.template';
                            $content = file_get_contents($template);
                            $view_list45 .= str_replace($search,$replace,$content);
                        }else{
                            $template = APP_PATH . 'Admin/View/Code/view_list4.template';
                            $content = file_get_contents($template);
                            $view_list45 .= str_replace($search,$replace,$content);
                        }
                        $template = APP_PATH . 'Admin/View/Code/view_list7.template';
                        $content = file_get_contents($template);
                        $view_list7 .= str_replace($search,$replace,$content);

                    }
                }
                //设置
                if(!empty($setField)){
                    foreach($setField as $sort){
                        $search = array('__FIELD__','__FIELD_TITLE__');
                        $replace = array($nameField[$sort],$titleField[$sort]);
                        $template = APP_PATH . 'Admin/View/Code/controller4.template';
                        $content = file_get_contents($template);
                        $controller4 .= str_replace($search,$replace,$content);

                        $template = APP_PATH . 'Admin/View/Code/controller5.template';
                        $content = file_get_contents($template);
                        $controller5 .= str_replace($search,$replace,$content);

                        $template = APP_PATH . 'Admin/View/Code/view_add2.template';
                        $content = file_get_contents($template);
                        $view_add2 .= str_replace($search,$replace,$content);

                        $template = APP_PATH . 'Admin/View/Code/view_edit2.template';
                        $content = file_get_contents($template);
                        $view_edit2 .= str_replace($search,$replace,$content);
                    }
                }
                $controller5 .= '            );';

                $controller_content = $controller1.$controller2.$controller3.$controller4.$controller5.$controller6.$controller4.$controller5.$controller7;
                $controllerFile = APP_PATH . 'Admin/Controller/'.$controllerName.'Controller.class.php';
                file_put_contents($controllerFile,$controller_content);
                echo '<p style="color:green">控制器文件'.$controllerFile.'生成成功</p>';ob_flush();flush();



                $file = APP_PATH . 'Admin/View/'.$controllerName;
                if(!is_dir($file)){
                    mkdir($file,0777,true);
                }
                $list_content = $view_list1.$view_list2.$view_list3.$view_list45.$view_list6.$view_list7.$view_list8;
                $listFile = $file.'/'.strtolower($controllerName).'list.html';
                file_put_contents($listFile,$list_content);
                echo '<p style="color:green">视图文件'.$listFile.'生成成功</p>';ob_flush();flush();

                $add_content = $view_add1.$view_add2.$view_add3;
                $addFile = $file.'/'.strtolower($controllerName).'add.html';
                file_put_contents($addFile,$add_content);
                echo '<p style="color:green">视图文件'.$addFile.'生成成功</p>';ob_flush();flush();

                $edit_content = $view_edit1.$view_edit2.$view_edit3;
                $editFile = $file.'/'.strtolower($controllerName).'edit.html';
                file_put_contents($editFile,$edit_content);
                echo '<p style="color:green">视图文件'.$editFile.'生成成功</p>';ob_flush();flush();

                sleep(1);
                /*添加菜单*/
                $menu = array(
                    'hide'=>$post['hide'],
                    'is_menu'=>1,
                    'pid'=>$post['pid'],
                    'sort'=>$post['sort'],
                    'tip'=>$post['tip'],
                    'title'=>$post['title'],
                    'url'=>'Admin/'.$controllerName.'/'.$controllerName.'List',
                );
                $Menu = D('Menu');
                $data = $Menu->create($menu);
                if($data){
                    $id = $Menu->add($menu);
                    if($id){
                        //记录行为
                        action_log('update_menu', 'Menu', $id, UID);
                        echo '<p style="color:green">菜单已经生成,即将刷新页面...</p>';ob_flush();flush();
                        sleep(1);
                        $this->redirect('Admin/AuthManager/authList',array('jump'=>1));

                    } else {
                        echo '<p style="color:red">菜单生成失败</p>';ob_flush();flush();
                    }
                } else {
                    echo '<p style="color:red">菜单生成失败,失败原因:'.$Menu->getError().'</p>';ob_flush();flush();
                }


            }else{
                $this->assign('step','field');
                $this->display();
            }
        }

    }

}